import type { IImagePos } from "@/types/utils";

export function __debounce(fn: Function, delay: number) {
  let timer: number | null = null;
  return function (this: unknown, ...args: any[]) {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
}

// 获取图片位置信息（过渡动画使用）
export function getImagePos(el: HTMLElement): IImagePos {
  const pos = el.getBoundingClientRect();
  return {
    width: pos.width,
    height: pos.height,
    left: Math.floor(pos.left),
    top: Math.floor(pos.top),
  };
}

// 图片预加载
export function imageIsLoading(src: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    img.onload = () => resolve(src);
    img.onerror = reject;
  });
}

// 观察dom是否进入视口，懒加载
export function domObserver(el: HTMLElement, cb: () => void) {
  const observer = new IntersectionObserver((entries) => {
    const isShow = entries.some((entry) => entry.intersectionRatio > 0);
    if (isShow) {
      observer.unobserve(el);
      cb();
    }
  });

  observer.observe(el);
}
